package com.aji.leather1.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.URLEncoder;
import java.util.Collections;

public class FileUtils {
    public static ResponseEntity<byte[]> transformFile(String filePath, String returnName) throws IOException {
        File file = new File(filePath);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 处理中文文件名兼容
        String encodedFileName = URLEncoder.encode(returnName, "UTF-8").replaceAll("\\+", "%20");
        headers.set("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
        headers.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));

        // 使用 try-with-resources 自动关闭流
        try (InputStream inputStream = new FileInputStream(file);
             ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {

            byte[] data = new byte[1024];
            int nRead;
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();

            return new ResponseEntity<>(buffer.toByteArray(), headers, HttpStatus.OK);
        }
    }


}
